//
//  RCDRCIMDelegateImplementation.m
//  RongCloud
//
//  Created by Liv on 14/11/11.
//  Copyright (c) 2014年 RongCloud. All rights reserved.
//

#import "DefaultPortraitView.h"
#import "RCDCommonDefine.h"
#import "RCDGroupInfo.h"
#import "RCDRCIMDataSource.h"
#import "RCDUserInfo.h"
#import "RCDUtilities.h"
#import "RCDataBaseManager.h"
#import <RongIMLib/RongIMLib.h>
#import "RCDUserInfoManager.h"
#import "SortForTime.h"

@interface RCDRCIMDataSource ()

@end

@implementation RCDRCIMDataSource

+ (RCDRCIMDataSource *)shareInstance {
  static RCDRCIMDataSource *instance = nil;
  static dispatch_once_t predicate;
  dispatch_once(&predicate, ^{
    instance = [[[self class] alloc] init];

  });
  return instance;
}

- (void)syncGroups {
  //开发者调用自己的服务器接口获取所属群组信息
    [[BQUserDao shareObject] getAllGroupInfoListWithUserId:[RCIM sharedRCIM].currentUserInfo.userId andServiceReceiveResponseSuccess:^(id response) {
        NSMutableArray *groupInfoList = response[@"groupInfoList"];
        for (NSMutableDictionary *groupInfo in groupInfoList) {
            
            RCDGroupInfo *rcGroupInfo = [[RCDGroupInfo alloc] init];
            rcGroupInfo.groupId = groupInfo[@"groupId"];
            rcGroupInfo.groupName = groupInfo[@"groupName"];
            rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
            rcGroupInfo.number = groupInfo[@"inNumber"];
            rcGroupInfo.maxNumber = groupInfo[@"maxNumber"];
            rcGroupInfo.introduce = groupInfo[@"introduce"];
            rcGroupInfo.creatorId = groupInfo[@"creatorId"];
            rcGroupInfo.creatorTime = groupInfo[@"creatorTime"];
            rcGroupInfo.isJoin = groupInfo[@"isJoin"];
            rcGroupInfo.isDismiss = groupInfo[@"isDismiss"];
            rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
            
            [[RCDataBaseManager shareInstance] insertGroupToDB:rcGroupInfo];
            
            //查询群组成员信息并插入本地数据库
            [[BQUserDao shareObject] queryGroupMemberListWithGroupId:rcGroupInfo.groupId andServiceReceiveResponseSuccess:^(id response) {
                
                NSMutableArray *members = [NSMutableArray array];
                NSArray *memberList = response[@"memberList"];
                for (NSDictionary *memberInfo in memberList)
                {
                    RCDUserInfo *member = [RCDUserInfo new];
                    member.userId = memberInfo[@"userId"];
                    member.name = memberInfo[@"userName"];
                    member.portraitUri = memberInfo[@"portraitUri"];
                    member.updatedAt = memberInfo[@"createTime"];
                    if (!member.portraitUri || member.portraitUri <= 0) {
                        member.portraitUri = [RCDUtilities defaultUserPortrait:member];
                    }
                    [members addObject:member];
                }
                SortForTime *sort = [[SortForTime alloc] init];
                members = [sort sortForUpdateAt:members order:NSOrderedDescending];
                [[RCDataBaseManager shareInstance] insertGroupMemberListToDB:members groupId:rcGroupInfo.groupId  complete:^(BOOL result) {
                }];
                
            } ServiceReceiveResponseFailed:^(id response) {
                
            }];
        }
    } ServiceReceiveResponseFailed:^(id response) {
        
    }];
}

- (void)syncGroupInfoWithGroupId:(NSString *)groupId complete:(void (^)(BOOL))completion
{
    [[BQUserDao shareObject] queryGroupInfoWithGroupId:groupId andServiceReceiveResponseSuccess:^(id response) {
        
        NSDictionary *groupInfo = response[@"groupInfo"];
        RCDGroupInfo *rcGroupInfo = [[RCDGroupInfo alloc] init];
        RCGroup *group = [[RCGroup alloc] initWithGroupId:groupId groupName:groupInfo[@"groupName"] portraitUri:groupInfo[@"portraitUri"]];
        rcGroupInfo.groupId = groupInfo[@"groupId"];
        rcGroupInfo.groupName = groupInfo[@"groupName"];
        rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
        rcGroupInfo.number = groupInfo[@"inNumber"];
        rcGroupInfo.maxNumber = groupInfo[@"maxNumber"];
        rcGroupInfo.introduce = groupInfo[@"introduce"];
        rcGroupInfo.creatorId = groupInfo[@"creatorId"];
        rcGroupInfo.creatorTime = groupInfo[@"creatorTime"];
        rcGroupInfo.isJoin = groupInfo[@"isJoin"];
        rcGroupInfo.isDismiss = groupInfo[@"isDismiss"];
        rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
        
        //同步到融云服务器
        [[RCIM sharedRCIM] refreshGroupInfoCache:group withGroupId:groupId];
        //同步到本地数据库
        [[RCDataBaseManager shareInstance] insertGroupToDB:rcGroupInfo];
        
        completion(YES);
        
    } ServiceReceiveResponseFailed:^(id response) {
        completion(NO);
    }];
}

//同步指定群组的信息,包括群组信息和成员信息
- (void)syncGroupMembersWithGroupId:(NSString *)groupId
                           complete:(void (^)(BOOL result))completion
{
    [[BQUserDao shareObject] queryGroupInfoWithGroupId:groupId andServiceReceiveResponseSuccess:^(id response) {
        
        NSDictionary *groupInfo = response[@"groupInfo"];
        RCDGroupInfo *rcGroupInfo = [[RCDGroupInfo alloc] init];
        RCGroup *group = [[RCGroup alloc] initWithGroupId:groupId groupName:groupInfo[@"groupName"] portraitUri:groupInfo[@"portraitUri"]];
        rcGroupInfo.groupId = groupInfo[@"groupId"];
        rcGroupInfo.groupName = groupInfo[@"groupName"];
        rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
        rcGroupInfo.number = groupInfo[@"inNumber"];
        rcGroupInfo.maxNumber = groupInfo[@"maxNumber"];
        rcGroupInfo.introduce = groupInfo[@"introduce"];
        rcGroupInfo.creatorId = groupInfo[@"creatorId"];
        rcGroupInfo.creatorTime = groupInfo[@"creatorTime"];
        rcGroupInfo.isJoin = groupInfo[@"isJoin"];
        rcGroupInfo.isDismiss = groupInfo[@"isDismiss"];
        rcGroupInfo.portraitUri = groupInfo[@"portraitUri"];
        
        //同步到融云服务器
        [[RCIM sharedRCIM] refreshGroupInfoCache:group withGroupId:groupId];
        //同步到本地数据库
        [[RCDataBaseManager shareInstance] insertGroupToDB:rcGroupInfo];
        
        [[BQUserDao shareObject] queryGroupMemberListWithGroupId:groupId andServiceReceiveResponseSuccess:^(id response) {
            
            NSMutableArray *result = [NSMutableArray array];
            NSArray *memberList = response[@"memberList"];
            for (NSDictionary *memberInfo in memberList)
            {
                RCUserInfo *member = [RCUserInfo new];
                member.userId = memberInfo[@"userId"];
                member.name = memberInfo[@"userName"];
                member.portraitUri = memberInfo[@"portraitUri"];
                
                [[RCIM sharedRCIM] refreshUserInfoCache:member withUserId:member.userId];
                
                [[RCIM sharedRCIM] refreshGroupUserInfoCache:member withUserId:member.userId withGroupId:groupId];
                [result addObject:member];
            }
            [[RCDataBaseManager shareInstance] insertGroupMemberListToDB:result groupId:groupId complete:^(BOOL result) {
                if (result) {
                    completion(YES);
                }
                else{
                    completion(NO);
                }
            }];
        } ServiceReceiveResponseFailed:^(id response) {
            completion(NO);
        }];
        
    } ServiceReceiveResponseFailed:^(id response) {
        completion(NO);
    }];
    
}

- (void)syncUserInfoWithUserId:(NSString *)userId complete:(void (^)(BOOL))completion
{
    [[BQUserDao shareObject] queryUserInfoWithUserId:userId andServiceReceiveResponseSuccess:^(id response) {
        
        EWUserInfo *user = [EWUserInfo mj_objectWithKeyValues:response[@"user"]];
        if (user == nil) {
            return;
        }
        RCUserInfo *rcUser = [RCUserInfo new];
        rcUser.userId = user.userId;
        rcUser.name = user.userName;
        rcUser.portraitUri = user.portraitUri;
        [[RCDataBaseManager shareInstance] insertUserToDB:rcUser complete:^(BOOL result) {
            if (result) {
                RCDUserInfo *friendInfo = [[RCDataBaseManager shareInstance] getFriendInfo:userId];
                if (friendInfo.name.length > 0) {
                    
                    friendInfo.displayName = user.userName;
                    friendInfo.name = user.userName;
                    friendInfo.portraitUri = user.portraitUri;
                    [[RCDataBaseManager shareInstance] insertFriendToDB:friendInfo];
                }
                [[RCIM sharedRCIM] refreshUserInfoCache:rcUser withUserId:userId];
            }
        }];
        
        completion(YES);
        
    } ServiceReceiveResponseFailed:^(id response) {
        completion(NO);
    }];
}

- (void)syncFriendList:(NSString *)userId
              complete:(void (^)(NSMutableArray *friends))completion {
    if (![userId isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
        return;
    }
    
    [[BQUserDao shareObject] queryFriendListWithfId:userId andServiceReceiveResponseSuccess:^(id response) {
        NSMutableArray *friends = [NSMutableArray array];
        NSMutableArray *rcUsers = [NSMutableArray array];
        NSMutableArray *Users = response[@"friendList"];
        for (NSDictionary *userinfo in Users) {
            RCDUserInfo *model = [[RCDUserInfo alloc] init];
            RCUserInfo *rcUser = [[RCUserInfo alloc] init];
            model.userId = userinfo[@"userId"];
            model.name = userinfo[@"userName"];
            model.portraitUri = userinfo[@"portraitUri"];
            model.status = userinfo[@"fstatus"];
            model.updatedAt = userinfo[@"createTime"];
            model.displayName = userinfo[@"userName"];
            [friends addObject:model];
            rcUser.userId = userinfo[@"userId"];
            rcUser.name = userinfo[@"userName"];
            rcUser.portraitUri = userinfo[@"portraitUri"];
            [rcUsers addObject:rcUser];
        }
        [[RCDataBaseManager shareInstance] insertUserListToDB:rcUsers complete:^(BOOL result) {
            
        }];
        [[RCDataBaseManager shareInstance] insertFriendListToDB:friends complete:^(BOOL result) {
            
        }];
        completion(friends);

    } ServiceReceiveResponseFailed:^(id response) {
        
    }];
}

#pragma mark - GroupInfoFetcherDelegate
- (void)getGroupInfoWithGroupId:(NSString *)groupId
                     completion:(void (^)(RCGroup *))completion {
  if ([groupId length] == 0)
    return;
    
    RCDGroupInfo *groupInfo = [[RCDataBaseManager shareInstance] getGroupByGroupId:groupId];
    if (groupInfo.groupName.length > 0) {
        RCGroup *group = [[RCGroup alloc] initWithGroupId:groupId groupName:groupInfo.groupName portraitUri:groupInfo.portraitUri];
        completion(group);
    }
    else
    {
        //开发者调自己的服务器接口根据userID异步请求数据
        [[BQUserDao shareObject] queryGroupInfoWithGroupId:groupId andServiceReceiveResponseSuccess:^(id response) {
            NSDictionary *groupInfo = response[@"groupInfo"];
            RCGroup *Group = [[RCGroup alloc] initWithGroupId:groupId groupName:groupInfo[@"groupName"] portraitUri:groupInfo[@"portraitUri"]];
            completion(Group);
        } ServiceReceiveResponseFailed:^(id response) {
            
        }];
    }
}
#pragma mark - RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId
                   completion:(void (^)(RCUserInfo *))completion {
  RCUserInfo *user = [RCUserInfo new];
  if (userId == nil || [userId length] == 0) {
    user.userId = userId;
    user.portraitUri = @"";
    user.name = @"";
    completion(user);
    return;
  }
  //开发者调自己的服务器接口根据userID异步请求数据
  if (![userId isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
    [[RCDUserInfoManager shareInstance] getFriendInfo:userId
                                                  completion:^(RCUserInfo *user) {
                                                    completion(user);
                                                  }];
  } else {
    [[RCDUserInfoManager shareInstance] getUserInfo:userId
                                         completion:^(RCUserInfo *user) {
                                           [[RCIM sharedRCIM]
                                            refreshUserInfoCache:user
                                            withUserId:user.userId];
                                           
                                            completion(user);
    }];
  }
  return;
}

#pragma mark - RCIMGroupUserInfoDataSource
/**
 *  获取群组内的用户信息。
 *  如果群组内没有设置用户信息，请注意：1，不要调用别的接口返回全局用户信息，直接回调给我们nil就行，SDK会自己巧用用户信息提供者；2一定要调用completion(nil)，这样SDK才能继续往下操作。
 *
 *  @param groupId  群组ID.
 *  @param completion 获取完成调用的BLOCK.
 */
- (void)getUserInfoWithUserId:(NSString *)userId
                      inGroup:(NSString *)groupId
                   completion:(void (^)(RCUserInfo *userInfo))completion {
    completion(nil);
}

- (void)getAllMembersOfGroup:(NSString *)groupId
                      result:(void (^)(NSArray *userIdList))resultBlock {
    
    [[BQUserDao shareObject] queryGroupMemberListWithGroupId:groupId andServiceReceiveResponseSuccess:^(id response) {
        
        NSMutableArray *result = [NSMutableArray array];
        NSArray *memberList = response[@"memberList"];
        for (NSDictionary *memberInfo in memberList)
        {
            RCUserInfo *member = [RCUserInfo new];
            member.userId = memberInfo[@"userId"];
            member.name = memberInfo[@"userName"];
            member.portraitUri = memberInfo[@"portraitUri"];
            [[RCIM sharedRCIM] refreshUserInfoCache:member withUserId:member.userId];
            [result addObject:member];
        }
        resultBlock(result);
    } ServiceReceiveResponseFailed:^(id response) {
        
    }];
}

- (NSArray *)getAllUserInfo:(void (^)())completion {
  return [[RCDataBaseManager shareInstance] getAllUserInfo];
}

- (NSArray *)getAllGroupInfo:(void (^)())completion {
  return [[RCDataBaseManager shareInstance] getAllGroup];
}

- (NSArray *)getAllFriends:(void (^)())completion {
  return [[RCDataBaseManager shareInstance] getAllFriends];
}

@end
